﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductionOrders;
using ERP_SaaS_WinForm.生产工单_报工_工序;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class SelectProductionOrder : Form
    {
        private string urls;
        private DataGridView dgvProductionOrders;
        private TextBox txtSearch;
        private Button btnSearch;
        private Button btnSelect;
        private Button btnCancel;
        private List<ProductionOrderData> productionOrderList;
        private HttpClient httpClient;

        public SelectProductionOrder()
        {
            InitializeComponent();
            InitializeCustomComponents();
            LoadProductionOrderData();
            urls = Apllo.ApiBaseUrl;
        }

        private void InitializeCustomComponents()
        {
            // 设置窗体属性
            this.Size = new Size(1200, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Text = "选择生产工单";

            // 创建控件
            dgvProductionOrders = new DataGridView();
            txtSearch = new TextBox();
            btnSearch = new Button();
            btnSelect = new Button();
            btnCancel = new Button();

            // 设置搜索区域
            Panel searchPanel = new Panel();
            searchPanel.Dock = DockStyle.Top;
            searchPanel.Height = 50;
            searchPanel.Padding = new Padding(10);

            Label lblSearch = new Label();
            lblSearch.Text = "搜索:";
            lblSearch.Location = new Point(10, 15);
            lblSearch.AutoSize = true;

            txtSearch.Location = new Point(60, 12);
            txtSearch.Size = new Size(200, 23);

            btnSearch.Text = "搜索";
            btnSearch.Location = new Point(270, 10);
            btnSearch.Size = new Size(60, 25);
            btnSearch.Click += BtnSearch_Click;

            searchPanel.Controls.AddRange(new Control[] { lblSearch, txtSearch, btnSearch });

            // 设置按钮区域
            Panel buttonPanel = new Panel();
            buttonPanel.Dock = DockStyle.Bottom;
            buttonPanel.Height = 50;
            buttonPanel.Padding = new Padding(10);

            btnSelect.Text = "选择";
            btnSelect.Location = new Point(1000, 10);
            btnSelect.Size = new Size(60, 25);
            btnSelect.Click += BtnSelect_Click;

            btnCancel.Text = "取消";
            btnCancel.Location = new Point(1070, 10);
            btnCancel.Size = new Size(60, 25);
            btnCancel.Click += BtnCancel_Click;

            buttonPanel.Controls.AddRange(new Control[] { btnSelect, btnCancel });

            // 设置DataGridView
            dgvProductionOrders.Dock = DockStyle.Fill;
            dgvProductionOrders.AllowUserToAddRows = false;
            dgvProductionOrders.AllowUserToDeleteRows = false;
            dgvProductionOrders.ReadOnly = true;
            dgvProductionOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvProductionOrders.MultiSelect = false;
            dgvProductionOrders.CellDoubleClick += DgvProductionOrders_CellDoubleClick;

            // 添加控件到窗体
            this.Controls.Add(dgvProductionOrders);
            this.Controls.Add(searchPanel);
            this.Controls.Add(buttonPanel);

            // 初始化HttpClient
            httpClient = new HttpClient();
        }

        private async void LoadProductionOrderData()
        {
            try
            {
                var response = await httpClient.GetAsync(urls+"/api/ProductionOrders/ProductionOrdersCommand");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"API返回的JSON: {json}");
                    
                    var apiResponse = JsonConvert.DeserializeObject<ApiProductionOrderResponse>(json);
                    
                    // 检查API响应状态
                    if (apiResponse != null)
                    {
                        Console.WriteLine($"API响应代码: {apiResponse.code}");
                        Console.WriteLine($"API响应消息: {apiResponse.message}");
                        
                        if (apiResponse.code == 200 || apiResponse.code == 0)
                        {
                            // 尝试解析不同的数据结构
                            List<ProductionOrderData> orders = null;
                            
                            if (apiResponse.data != null)
                            {
                                try
                                {
                                    // 尝试解析为分页数据结构
                                    var pageDataJson = JsonConvert.SerializeObject(apiResponse.data);
                                    var pageData = JsonConvert.DeserializeObject<ProductionOrderPageData>(pageDataJson);
                                    
                                                                         if (pageData != null && pageData.pageDatas != null)
                                     {
                                         orders = pageData.pageDatas;
                                         Console.WriteLine($"解析为分页数据，共 {orders.Count} 条记录");
                                     }
                                }
                                catch
                                {
                                    try
                                    {
                                        // 尝试解析为简单数组结构
                                        var simpleJson = JsonConvert.SerializeObject(apiResponse.data);
                                        orders = JsonConvert.DeserializeObject<List<ProductionOrderData>>(simpleJson);
                                        Console.WriteLine($"解析为简单数组，共 {orders?.Count ?? 0} 条记录");
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"解析数据结构失败: {ex.Message}");
                                    }
                                }
                            }
                            
                            if (orders != null && orders.Count > 0)
                            {
                                productionOrderList = orders;
                                SetupDataGridView();
                                LoadDataToGrid();
                                Console.WriteLine($"成功加载 {productionOrderList.Count} 条生产工单数据");
                            }
                            else
                            {
                                // 如果没有数据，显示空列表
                                productionOrderList = new List<ProductionOrderData>();
                                SetupDataGridView();
                                LoadDataToGrid();
                                MessageBox.Show("暂无生产工单数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show($"API返回错误: {apiResponse.message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("API响应解析失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"HTTP请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"异常详情: {ex}");
                MessageBox.Show($"加载生产工单数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SetupDataGridView()
        {
            dgvProductionOrders.Columns.Clear();
            dgvProductionOrders.AutoGenerateColumns = false;

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ProductionOrdersCode",
                HeaderText = "工单编号",
                Width = 120
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ProductionOrdersName",
                HeaderText = "工单名称",
                Width = 150
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ProductName",
                HeaderText = "产品名称",
                Width = 120
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "PlannedQuantity",
                HeaderText = "计划数量",
                Width = 80
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ActualQuantity",
                HeaderText = "实际数量",
                Width = 80
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "State",
                HeaderText = "工单状态",
                Width = 80
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "PlanStart",
                HeaderText = "计划开工时间",
                Width = 120
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "PlanEnd",
                HeaderText = "计划完工时间",
                Width = 120
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ActualStart",
                HeaderText = "实际开工时间",
                Width = 120
            });

            dgvProductionOrders.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ActualEnd",
                HeaderText = "实际完工时间",
                Width = 120
            });
        }

        private void LoadDataToGrid()
        {
            if (productionOrderList != null)
            {
                dgvProductionOrders.DataSource = productionOrderList;
            }
        }

        private void BtnSearch_Click(object sender, EventArgs e)
        {
            if (productionOrderList != null)
            {
                var filteredList = productionOrderList.Where(p => 
                    string.IsNullOrEmpty(txtSearch.Text) ||
                    (p.ProductionOrdersCode?.ToLower().Contains(txtSearch.Text.ToLower()) == true) ||
                    (p.ProductionOrdersName?.ToLower().Contains(txtSearch.Text.ToLower()) == true) ||
                    (p.ProductName?.ToLower().Contains(txtSearch.Text.ToLower()) == true)
                ).ToList();

                dgvProductionOrders.DataSource = filteredList;
            }
        }

        private void DgvProductionOrders_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                BtnSelect_Click(sender, e);
            }
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            if (dgvProductionOrders.CurrentRow != null)
            {
                SelectedProductionOrder = dgvProductionOrders.CurrentRow.DataBoundItem as ProductionOrderData;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("请选择一个生产工单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        public ProductionOrderData SelectedProductionOrder { get; private set; }
    }
}
